package com.project.service;

import com.project.common.utils.Constants;
import com.project.common.utils.FileUtils;
import com.project.common.utils.Util;
import com.project.dao.InternInfoMapper;
import com.project.entity.*;
import com.project.entity.Class;
import com.project.myBeans.InternInfoDetail;
import com.project.myBeans.InternReportEntity;
import com.project.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: TateBrown
 * @date: 2018/5/26 13:53
 * @param:
 * @return:
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class InternInfoServiceImpl extends BaseService implements InternInfoService {
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private OrgInfoService orgInfoService;
    @Autowired
    private ImagesService imagesService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClassService classService;
    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private  InternInfoMapper internInfoMapper;

    @Override
    public InternInfo findById(int id) {
        return internInfoMapper.selectByPrimaryKey(id);
    }

//    @Override
//    public int modify(InternInfo internInfo) {
//
//        return internInfoMapper.updateByPrimaryKeySelective(internInfo);
//    }

//    @Override
//    public int add(InternInfo internInfo) {
//
//        return internInfoMapper.insertSelective(internInfo);
//    }

    @Override
    public int modify(InternInfo internInfo) throws IOException {
        internInfoMapper.updateByPrimaryKeySelective(internInfo);
        //工作环境
        if (!StringUtils.isEmpty(internInfo.getWorkingpicBase64())) {
            //1. 获取root上级目录
            String rootPath = Util.getWebRootURL(this);

            //2. 获取下级目录
            String subPath = configParameters.getWorkingPicSubPath();
            //3. 获取文件格式
            String ext = Util.getBase64StringExt(internInfo.getWorkingpicBase64());
            //4. 设置文件名称
            String fileNamePrefix = "workingpic_intern_";
            String fileName = fileNamePrefix + internInfo.getId() + "." + ext;
            //5. 创建文件
            String outBase64Str = Util.getBase64StringData(internInfo.getWorkingpicBase64());
            FileUtils.writeDecodeBase64StrToFile(rootPath + subPath + fileName, outBase64Str);

            Image image = new Image();
            image.setPath(fileName);
            if (internInfo.getWorkingpic() == null) { //若无上传图片
                image.setCategory(3); //工作环境
                imagesService.add(image);
                internInfo.setWorkingpic(image.getId());
                internInfoMapper.updateByPrimaryKeySelective(internInfo);
            } else { //若先前已上传图片
                image.setId(internInfo.getWorkingpic());
                imagesService.update(image);
            }
        }
        return 1;
    }

    @Override
    public int add(InternInfo internInfo) throws IOException {
        internInfoMapper.insertSelective(internInfo);
        if (!StringUtils.isEmpty(internInfo.getWorkingpicBase64())) {
            //1. 获取root上级目录
            String rootPath = Util.getWebRootURL(this);
            //2. 获取下级目录
            String subPath = configParameters.getWorkingPicSubPath();
            //3. 获取文件格式
            String ext = Util.getBase64StringExt(internInfo.getWorkingpicBase64());
            //4. 设置文件名称
            String fileNamePrefix = "workingpic_intern_";
            String fileName = fileNamePrefix + internInfo.getId() + "." + ext;
            //5. 创建文件
            String outBase64Str = Util.getBase64StringData(internInfo.getWorkingpicBase64());
            FileUtils.writeDecodeBase64StrToFile(rootPath + subPath + fileName, outBase64Str);

            //插入图片记录
            Image image = new Image();
            image.setPath(fileName);
            image.setCategory(3); //工作环境
            imagesService.add(image);
            System.out.println(image.getId());

            //插入imageId
            internInfo.setWorkingpic(image.getId());
            internInfoMapper.updateByPrimaryKeySelective(internInfo);
        }
        return 1;
    }

    @Override
    public int delete(int id) {
        return internInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<InternInfo> findall() {
        return internInfoMapper.selectAll();
    }

    @Override
    public List<InternInfo> findByCondition(InternInfo internInfo) {
        return internInfoMapper.selectByCondition(internInfo);
    }

    /**
     * author: WheelChen
     * date: 2017/6/30
     * function: 根据实习信息id查找实习详细信息
     *
     * @param id 实习信息id
     * @return
     */
    @Override
    public InternInfoDetail findDetailById(Integer id) throws Exception {
        InternInfoDetail internInfoDetail = new InternInfoDetail();
        InternInfo internInfo = findById(id);
        internInfoDetail.setInternInfo(internInfo);
        if (internInfo.getSno() != null)
            internInfoDetail.setStudentInfoDetail(studentInfoService.findDetailById(internInfo.getSno()));
        if (internInfo.getOrgid() != null)
            internInfoDetail.setOrgInfo(orgInfoService.findByid(internInfo.getOrgid()));
        if (internInfo.getWorkingpic() != null) {
            Image workingPic = imagesService.findById(internInfo.getWorkingpic());
            workingPic.setPath(configParameters.getServer() + configParameters.getWorkingPicSubPath() + workingPic.getPath());
            internInfoDetail.setImage(workingPic);
        }

        return internInfoDetail;
    }

    /**
     * author: WheelChen
     * date: 2017/7/27
     * function: 根据实习生id(sno)和实习单位类别查找正在实习的实习信息
     *
     * @param internInfo
     * @return
     */
    @Override
    public InternInfo findOneBySnoAndOragattr(InternInfo internInfo) {
        return internInfoMapper.selectOneBySnoAndOragattr(internInfo);
    }

    /**
     * author: WheelChen
     * date: 2017/8/3
     * function: 查找审核中的实习信息
     *
     * @param internInfo
     * @return
     */
    @Override
    public InternInfo findOneBySnoAndReview(InternInfo internInfo) {
        return internInfoMapper.selectOneBySnoAndReview(internInfo);
    }

    /**
     * author: WheelChen
     * date: 2017/8/9
     * function: 判断是否处于审核流程中
     *
     * @param internInfo
     * @return ture - 不处于 false - 处于
     */
    @Override
    public boolean checkIsUnderReview(InternInfo internInfo) {

        boolean flag = false;
        if (internInfoMapper.selectOneBySnoAndReview(internInfo) != null) {
            flag = true;
        }

        return flag;
    }

    /**
     * author: WheelChen
     * date: 2017/9/19
     * function: 根据实习生idList批量删除
     *
     * @param snoList
     * @return
     */
    @Override
    public int removeBatchBySnoList(List snoList) {
        return internInfoMapper.deleteBatchBySnoList(snoList);
    }

    /**
     * 根据用户idList查找实习安排表
     *
     * @param userIds 用户id列表
     * @return
     */
    @Override
    public List<InternReportEntity> findBatchByUserIds(List<Integer> userIds) {

        List<InternReportEntity> internReportEntityList = new ArrayList<>();

        for (Integer userId : userIds) {
            InternReportEntity internReportEntity = new InternReportEntity();


            try {
                //获取 姓名、性别、联系电话
                User user = userService.findOneByUserID(userId);
                internReportEntity.setUser(user);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //学号
            StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);
            internReportEntity.setStudentInfo(studentInfo);

            //班级名称
            if (studentInfo.getClassid() != null) {
                Class clazz = classService.findOne(studentInfo.getClassid());
                if (clazz != null) {
                    internReportEntity.setClassName(clazz.getName());
                }
            }
            //获取校内指导老师名称
            if (studentInfo.getInternadvisor() != null) {
                TeacherInfo teacherInfo = teacherInfoService.findOne(studentInfo.getInternadvisor());
                if (teacherInfo != null) {
                    try {
                        User teacherUser = userService.findOneByUserID(teacherInfo.getUserid());
                        if (teacherUser != null) {
                            internReportEntity.setTeacherName(teacherUser.getRealname());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            //查询**当前**实习单位相关信息
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo.getId());
            //当前实习单位
            internInfo.setOrgattr(Constants.ORGATTR.NOW.value());

            List<InternInfo> internInfoList = internInfoMapper.selectByCondition(internInfo);
            if (internInfoList.size() > 0) {
                InternInfo internInfo1 = internInfoList.get(0);
                //实习类型、实习单位指导老师、实习单位指导老师联系电话
                internReportEntity.setInternInfo(internInfo1);
                //实习单位名称
                OrgInfo orgInfo = orgInfoService.findByid(internInfo1.getOrgid());
                internReportEntity.setOrgInfo(orgInfo);
            }

            internReportEntityList.add(internReportEntity);
        }
        return internReportEntityList;
    }
}

